package com.soft.util;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.FileImageInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.dom4j.Document;
import org.dom4j.DocumentFactory;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class Handle {

	/**
	 * 統一path路徑"\"
	 * 
	 * @param path
	 * @return
	 */
	public static String passpath2(String path) {
		boolean flag = true;
		path = passpath(path);
		while (flag) {
			path = path.replace("/", "\\");
			if (path.indexOf("/") == -1 && path.indexOf("//") == -1) {
				flag = false;
			}
		}
		return path;
	}

	/**
	 * 統一path路徑"/"
	 * 
	 * @param path
	 * @return
	 */
	public static String passpath(String path) {
		boolean flag = true;
		while (flag) {
			path = path.replace("\t", "/t");
			path = path.replace("\\", "/");
			path = path.replace("//", "/");
			if (path.indexOf("\\") == -1 && path.indexOf("//") == -1) {
				flag = false;
			}
		}
		return path;
	}

	/**
	 * 統一文件路徑，只可用於文件路徑，其他路徑不適用
	 * 
	 * @param path
	 * @return
	 */
	public static String formatPath(String path) {
		// 將所有"\"替換為"/"
		path = path.replaceAll("\\\\", "/");
		// 將所有重複"/"替換為單"/"
		path = path.replaceAll("(\\/{2,})+", "/");
		// 去掉路徑最後的"/"
		if (path.endsWith("/")) {
			path = path.substring(0, path.lastIndexOf("/"));
		}

		return path;
	}

	/**
	 * 转换 为liunx 操作系统路径
	 * 
	 * @param path
	 *          需转换的路径
	 * @return smb://192.168.41.229/gztohk//daban
	 * 
	 */
	public static String TranLinuxPath(String path, int sep) {
		if (path != null && path.trim().length() != 0) {
			boolean flag = true;
			while (flag) {
				path = path.replace("\\", "/");
				path = path.replace("//", "/");
				if (path.indexOf("\\") == -1 && path.indexOf("//") == -1) {
					flag = false;
				}
			}
			if (path.toLowerCase().indexOf("smb:") == -1) {
				path = "smb:" + "/" + path;
			} else {
				path = "smb:" + "/" + path.substring(4, path.length());
			}
			if (sep == 1) {
				if (!path.endsWith("/")) {
					File file = new File(path);
					if (file != null && !file.isFile()) {
						path += "/";
					}
				}
			}
		}
		return path;
	}

	public static long getLong(String str) {
		str = trim(str);
		try {
			return Long.valueOf(str);
		} catch (Exception e) {
			return 0;
		}
	}

	/**
	 * 寫xml到流
	 * 
	 * @param out
	 * @param doc
	 * @param encoding
	 */
	public static void writeXml(OutputStream out, Document doc, String encoding) {
		try {
			OutputFormat format = OutputFormat.createPrettyPrint();
			format.setEncoding(encoding);
			XMLWriter writer = null;
			try {
				writer = new XMLWriter(out, format);
				writer.write(doc);
				writer.flush();
				out.flush();
			} finally {
				if (writer != null) {
					writer.close();
				}

				if (out != null) {
					out.close();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 向客戶端發送狀態代碼
	 * 
	 * @param out
	 *          輸出流
	 * @param flag
	 *          狀態碼
	 */
	public static void sendStatusXml(OutputStream out, int flag) {
		Document doc = DocumentFactory.getInstance().createDocument();
		Element status = doc.addElement("status");
		Element value = status.addElement("value");
		value.addText(String.valueOf(flag));
		writeXml(out, doc, "utf-8");
	}

	/**
	 * 向客戶端發送狀態代碼(0,1)
	 * 
	 * @param response
	 * @param flag
	 */
	public static void sendStatusXml(HttpServletResponse response, boolean flag) {
		DocumentFactory factory = DocumentFactory.getInstance();
		Document doc = factory.createDocument();
		Element status = doc.addElement("status");
		Element value = status.addElement("value");
		if (flag) {
			value.addText("1");// 成功
		} else {
			value.addText("0");// 失敗
		}

		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("UTF-8");

		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/xml; charset=UTF-8");
		Writer rewriter;
		try {
			rewriter = response.getWriter();
			XMLWriter writer = new XMLWriter(rewriter, format);
			writer.write(doc);
			writer.flush();
			writer.close();

			rewriter.flush();
			rewriter.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 創建圖片縮略圖
	 * 
	 * @param inpath
	 *          圖片輸入路徑
	 * @param outpath
	 *          圖片輸出路徑
	 * @param maxlength
	 *          設置縮略圖最大邊的值
	 * @param dpi
	 *          設置縮略圖的dpi
	 */
	public static void createimg(String inpath, String outpath, Integer maxlength, Integer dpi) {
		try {
			File infile = new File(inpath);
			File outfile = new File(outpath);

			ImageReader reader = ImageIO.getImageReadersByFormatName("jpeg").next();

			reader.setInput(new FileImageInputStream(infile), true, false);

			// IIOMetadata data = reader.getImageMetadata(0);
			BufferedImage image = reader.read(0);

			int width = image.getWidth(null);
			int height = image.getHeight(null);

			int w = -1, h = -1;
			if (width > height) {
				w = maxlength;
			} else {
				h = maxlength;
			}

			Image rescaled = image.getScaledInstance(w, h, Image.SCALE_AREA_AVERAGING);
			BufferedImage output = toBufferedImage(rescaled, BufferedImage.TYPE_INT_RGB);

			// int width = rescaled.getWidth(null);
			// int height = rescaled.getHeight(null);
			// BufferedImage output = new BufferedImage(width, height,
			// BufferedImage.TYPE_INT_RGB);
			// Graphics2D g = output.createGraphics();
			// g.drawImage(image, 0, 0, null);
			// g.dispose();

			FileOutputStream fos = new FileOutputStream(outfile);
			JPEGImageEncoder jpegEncoder = JPEGCodec.createJPEGEncoder(fos);
			JPEGEncodeParam jpegEncodeParam = jpegEncoder.getDefaultJPEGEncodeParam(output);
			jpegEncodeParam.setDensityUnit(JPEGEncodeParam.DENSITY_UNIT_DOTS_INCH);
			jpegEncodeParam.setXDensity(dpi);
			jpegEncodeParam.setYDensity(dpi);
			jpegEncoder.encode(output, jpegEncodeParam);
			fos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static BufferedImage toBufferedImage(Image image, int type) {
		int w = image.getWidth(null);
		int h = image.getHeight(null);
		BufferedImage result = new BufferedImage(w, h, type);
		Graphics2D g = result.createGraphics();
		g.drawImage(image, 0, 0, null);
		g.dispose();
		return result;
	}

	/** 為空時返回true */
	public static boolean isNull(String arg) {
		if (arg == null)
			return true;
		if ("".equals(arg))
			return true;
		if ("".equals(arg.trim()))
			return true;
		return false;
	}

	/** 去空格. */
	public static String trim(String arg) {
		return isNull(arg) ? null : arg.trim();
	}

	public static String getString2(Object obj) {
		if (obj != null && !obj.equals("") && !obj.equals("null")) {
			return obj.toString().trim();
		}
		return "";
	}

	public static String getString(String str) {
		if (str != null && !str.equals("") && !str.equals("null")) {
			return str.trim();
		}
		return "";
	}

	public static String getString1(String str) {
		if (str != null && !str.equals("") && !str.equals("null")) {
			return str.trim();
		}
		return null;
	}

	public static String getInteger1(int id) {
		try {
			if (id == 0) {
				return "";
			} else {
				return id + "";
			}
		} catch (Exception e) {
		}
		return "";
	}

	public static String getFloat1(float value) {
		try {
			if (value == 0f) {
				return "";
			} else {
				return value + "";
			}
		} catch (Exception e) {
		}
		return "";
	}

	public static String getUploadFileName(String name) {
		try {
			Date date = new Date();
			SimpleDateFormat simpleDF = new SimpleDateFormat("yyyyMMddHHmmss");
			String str = (Math.random() * 10000) + "";
			str = str.substring(0, 4);
			name = name.substring(name.lastIndexOf("."), name.length());
			return simpleDF.format(date).toString() + str + name;
		} catch (Exception e) {
		}

		return name;
	}

	/**
	 * 向頁面發送指定消息 message
	 * 
	 * @param response
	 * @param message
	 */
	public static void sendMessage(HttpServletResponse response, String message) {

		Writer writer = null;
		try {
			response.setContentType("text/html; charset=UTF-8"); //$NON-NLS-1$
			writer = response.getWriter();
			writer.write(message);
			writer.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (writer != null) {
				try {
					writer.close();
				} catch (IOException e) {
				}
				writer = null;
			}
		}
	}

	/**
	 * 寫出文件
	 * 
	 * @param str
	 * @param filePath
	 */
	public static void outputFile(String str, String filePath) {
		FileOutputStream fos = null;
		Writer out = null;
		try {
			fos = new FileOutputStream(filePath);
			out = new OutputStreamWriter(fos, "utf-8");
			out.write(str);
			out.close();
			fos.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
				}
			}
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
				}
			}
		}
	}

	/**
	 * 上傳 (2010.09.23改)
	 * 
	 * @param preview
	 * @param PreviewFileName
	 * @return
	 */
	public static void uploadFile(File preview, String path, String PreviewFileName) {
		try {
			InputStream is = openInputStream(preview);
			try {
				OutputStream os = openOutputStream(new File(path, PreviewFileName));
				try {
					copy(is, os);
				} finally {
					closeQuietly(os);
				}
			} finally {
				closeQuietly(is);
			}
		} catch (Exception e) {

		}
	}

	/**
	 * 直接上傳至指定目錄
	 * 
	 * @param file
	 * @param outFilepath
	 */
	public static void uploadFile(File file, String outFilepath) {
		InputStream in = null;
		OutputStream out = null;

		String parentpath = new File(outFilepath).getParent();
		File fi = new File(parentpath);
		if (!fi.exists())
			fi.mkdirs();

		try {
			// 寫文件到服務器
			in = new FileInputStream(file);
			out = new FileOutputStream(outFilepath);
			byte[] temp = new byte[1024];
			int len = -1;
			while ((len = in.read(temp)) != -1) {
				out.write(temp, 0, len);
			}
			out.flush();
		} catch (Exception e) {
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
				}
			}
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
				}
			}
		}
	}

	public static List getElementvalueids(String strs) {
		if (strs != null && !strs.trim().equals("")) {
			List list = null;
			try {
				list = new ArrayList();
				String str[] = Handle.getArrString(strs, "_");
				for (int i = 0; i < str.length; i++) {
					if (str[i] != null && !str[i].trim().equals("")) {
						list.add(str[i]);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return list;
		}
		return null;
	}

	public static String add_separator(String path) {
		if (path != null && !path.trim().equals("")) {
			path = path.trim();
			if (!path.endsWith("\\") && !path.endsWith("/")) {
				path = path + File.separator;// 在 UNIX 系统上，此字段的值为 '/'；在
				// Microsoft Windows 系统上，它为
				// '\\'。
			}
			return path;
		}
		return null;
	}

	public static String filterstring(String source, String split) {
		String[] strs = source.split(split);
		Set<String> set = new HashSet<String>();
		if (strs != null) {
			for (int i = 0; i < strs.length; i++) {
				if (!"".equals(strs[i])) {
					set.add(strs[i]);
				}
			}
		}
		StringBuffer dest = new StringBuffer();
		for (String str : set) {
			dest.append(str).append(",");
		}
		return dest.toString();
	}

	public static String Replace(String s, String s1, String s2) {
		StringBuffer stringbuffer = new StringBuffer();
		int i = s2.indexOf(s);
		if (i == -1) {
			return s2;
		}
		stringbuffer.append(s2.substring(0, i) + s1);
		if (i + s.length() < s2.length()) {
			stringbuffer.append(Replace(s, s1, s2.substring(i + s.length(), s2.length())));
		}
		return stringbuffer.toString();
	}

	public static String RetrunTX(String s) {
		return Replace("\"", "\\\"", Replace("'", "\\'", Replace("\\", "\\\\", s)));
	}

	public static boolean copyFile(String resource, String destination) {
		DataOutputStream out = null;
		DataInputStream in = null;
		try {
			File fileR = new File(destination);
			String parent = fileR.getParent();
			File fi = new File(parent);
			if (!fi.exists())
				fi.mkdirs();
			in = new DataInputStream(new BufferedInputStream(new FileInputStream(resource)));
			File file = new File(destination);
			if (!file.exists()) {
				file.createNewFile();
			}

			out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(destination)));
			byte[] buffer = new byte[1024 * 1024 * 10];
			int k = in.read(buffer);
			while (k != -1) {
				out.write(buffer, 0, k);
				out.flush();
				k = in.read(buffer);
			}

		} catch (Exception e) {
			// System.out.println("找不到===" + resource);
			// TODO Auto-generated catch block
			return false;
			// e.printStackTrace();

		} finally {
			try {
				if (out != null) {
					out.close();
				}
			} catch (IOException e) {
			}
			try {
				if (in != null) {
					in.close();
				}
			} catch (IOException e) {
			}
		}
		return true;

	}

	public static String transitionPath(String path, String os) {
		if (path != null && os != null) {
			String path_attribute = isWindowsOrLinuxPath(path);
			if (os != null && os.trim().equals("linux")) {
				if (path_attribute != null && path_attribute.equals("linux")) { // 路徑本身就是linux路徑，不需要轉換，直接返回
					path = path.replace('\\', '/');
					return path.trim();
				} else if (path_attribute != null && path_attribute.equals("windows")) {// 路徑是windows路徑，需要轉換成linux路徑
					path = "smb:" + path.replace('\\', '/');
				}

			} else if (os != null && os.trim().equals("windows")) {
				if (path_attribute != null && path_attribute.equals("windows")) { // 路徑本身就是windows路徑，不需要轉換，直接返回
					path = path.replace('/', '\\');
					return path.trim();
				} else if (path_attribute != null && path_attribute.equals("linux")) {// 路徑是linux路徑，需要轉換成windows路徑
					path = path.replaceAll("smb:", "");
					path = path.replaceAll("SMB:", "");
					path = path.replace('/', '\\');
				}
			}
			return path.trim();
			// return UserUtil.TrPath(os, path);
		}
		return null;
	}

	public static String isWindowsOrLinuxPath(String path) {
		if (path != null && path.trim().lastIndexOf("\\\\") > -1) {
			return "windows";
		} else if (path != null && path.trim().lastIndexOf("//") > -1) {
			return "linux";
		}
		return null;
	}

	public static String getOSName() {
		String os = System.getProperty("os.name");
		if (os != null && os.toLowerCase().contains("linux")) {
			return "linux";
		} else {
			return "windows";
		}
	}

	public static String replaceLign(String str, String key) {
		return Replace(key.toLowerCase(), "<font color=red>" + key + "</font>", str.toLowerCase());
	}

	public static boolean checkObjectIsNull(Object object) {
		if (object != null && !object.toString().trim().equals("")) {
			return true;
		}
		return false;
	}

	// 检查字符串是否是整形
	public static boolean checkInt(String str) {
		try {
			Integer.parseInt(str.trim());
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	// 检查字符串是否是长整形
	public static boolean checkLong(String str) {
		try {
			Long.parseLong(str.trim());
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	public static Float getFloat(String str, Float defaultValue) {
		try {
			return Float.valueOf(str);
		} catch (Exception e) {
			return defaultValue;
		}
	}

	public static float getfloat(String str) {
		try {

			DecimalFormat myformat = new DecimalFormat("######0.00");
			Number strss = myformat.parse(str.trim());
			// System.out.println(strss.floatValue());

			return strss.floatValue();
			// return Float.valueOf();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 0f;
	}

	public static Float getfloat2(float str) {
		try {

			DecimalFormat myformat = new DecimalFormat("######0.00");
			Number strss = myformat.parse(str + "");
			// System.out.println(strss.floatValue());

			return strss.floatValue();
			// return Float.valueOf();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 1f;
	}

	public static String getfloatstr(float num) {
		double d = div(num, 1, 2);
		return d + "";
	}

	/**
	 * 提供（相对）精确的除法运算。当发生除不尽的情况时，由scale参数指 定精度，以后的数字四舍五入。
	 * 
	 * @param v1
	 *          被除数
	 * @param v2
	 *          除数
	 * @param scale
	 *          表示表示需要精确到小数点以后几位。
	 * @return 两个参数的商
	 */

	public static double div(double v1, double v2, int scale) {
		if (scale < 0) {
			throw new IllegalArgumentException("The scale must be a positive integer or zero");
		}
		BigDecimal b1 = new BigDecimal(Double.toString(v1));
		BigDecimal b2 = new BigDecimal(Double.toString(v2));
		return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
	}

	/**
	 * 計算在指定的一個時間內完成一個指定的數量要花費的時間/實際要印刷的數量
	 * 
	 * @param costTime
	 *          指定的時間
	 * @param number
	 *          指定的數量
	 * @param printnumber
	 *          實際要印刷的數量
	 * @return
	 */

	// 將分鐘轉化為小時
	public static String minuteTOHour(int minute) {
		String hour = null;
		if (minute > 0) {
			if (minute > 60) {
				hour = (minute / 60) + "小時" + (minute % 60) + "分";
				if ((minute / 60) > 24) {
					hour = (minute / 60) / 24 + "天" + (minute / 60) % 24 + "小時" + (minute % 60) + "分";
				}
			} else {
				hour = minute + "分";
			}
		} else {
			hour = "0分";
		}

		return hour;
	}

	// 从小到大排序 int
	public static int[] sort(int[] arr) {
		for (int i = 0; i < arr.length; i++) {
			for (int j = i; j < arr.length; j++) {
				if (arr[i] > arr[j]) {
					int x = arr[i];
					arr[i] = arr[j];
					arr[j] = x;
				}
			}
		}
		return arr;
	}

	// 時間的加減 +2 表示加2天，-2表示減2天
	public static String add_minus(Date date, int how) {
		if (date != null)
			return DateToStr(new Date(date.getTime() + how * 24 * 60 * 60 * 1000));
		return null;
	}

	// 从小到大排序 long
	public static long[] sort(long[] arr) {
		for (int i = 0; i < arr.length; i++) {
			for (int j = i; j < arr.length; j++) {
				if (arr[i] > arr[j]) {
					long x = arr[i];
					arr[i] = arr[j];
					arr[j] = x;
				}
			}
		}
		return arr;
	}

	public static int costTime(int costTime, int number, int machinnumber) {
		int ct = 0;
		double b = Handle.div(costTime, number, 10);
		double c = b * machinnumber;
		double h = Handle.div(c, 1, 0); // 將需要用的時間四舍五入
		ct = (int) h;
		return ct;
	}

	public static Integer[] getIntegers(String[] str) {
		if (str != null) {
			Integer tt[] = new Integer[str.length];
			for (int i = 0; i < str.length; i++) {
				tt[i] = getInteger(str[i]);
			}
			return tt;
		}
		return null;
	}

	public static List getIntegersList(String[] str) {
		if (str != null) {
			List list = new ArrayList();
			for (int i = 0; i < str.length; i++) {
				list.add(getInteger(str[i]));
			}
			return list;
		}
		return null;
	}

	public static Integer getInteger(String str) {
		try {
			return new Integer(str.trim());
		} catch (Exception e) {
		}
		return null;
	}

	public static Integer getInteger1(String str) {
		try {
			return new Integer(str.trim());
		} catch (Exception e) {
		}
		return -1;
	}

	public static Integer getInteger2(Object obj) {
		if (obj != null && !obj.equals("") && !obj.equals("null")) {
			return new Integer(obj.toString().trim());
		}
		return null;
	}

	public static Integer getInteger(String str, Integer def) {
		Integer rint = getInteger(str);
		if (rint != null)
			return rint;
		return def;
	}

	public static Integer[] getArrInteger(String str) {
		StringTokenizer sto = new StringTokenizer(str, ",");
		Integer rr[] = new Integer[sto.countTokens()];
		int i = 0;
		while (sto.hasMoreTokens()) {
			rr[i] = getInteger(sto.nextToken());
			i++;
		}
		return rr;
	}

	public static String strDistinct(String str) {
		String[] strArr = str.split(",");
		String strAim = ",";
		for (int i = 0; i < strArr.length; i++) {
			if (strArr[i].equals(""))
				continue;
			if (strAim.indexOf("," + strArr[i] + ",") == -1) {
				strAim = strAim + strArr[i] + ",";
			}
		}
		if (!strAim.equals(","))
			strAim = strAim.substring(1, strAim.length() - 1);
		else
			strAim = "";
		return strAim;
	}

	public static String replace(String arg) {
		if (arg == null) {
			return "";
		} else {
			byte[] bs = arg.getBytes();
			int j = 0;
			byte[] temp = new byte[bs.length];
			for (int i = 0; i < bs.length; i++) {
				if (0 < bs[i] && bs[i] <= 32) {
					// bs[i]=0;
				} else if (bs[i] == 127) {
					// bs[i]=0;
				} else if (bs[i] >= 128) {
					// bs[i]=0;
				} else {
					temp[j] = bs[i];
					// System.out.println(bs[i]);
					j++;
				}
			}
			if (j > 0) {
				return new String(temp, 0, j);
			} else {
				return "";
			}
		}
	}

	public static String[] getArrString(String str, String split) {
		StringTokenizer sto = new StringTokenizer(str, split);
		String rr[] = new String[sto.countTokens()];
		int i = 0;
		while (sto.hasMoreTokens()) {
			rr[i] = sto.nextToken();
			i++;
		}
		List list = new ArrayList();
		for (int j = 0; j < rr.length; j++) {
			list.add(rr[j]);
		}
		for (int j = 0; j < list.size(); j++) {
			for (int k = 0; k < j; k++) {
				if (list.get(j).toString().equalsIgnoreCase(list.get(k).toString())) {
					list.remove(j);
					j--;
					break;
				}
			}
		}
		String kkr[] = new String[list.size()];
		list.toArray(kkr);
		return kkr;
	}

	public static String[] getArrString(String str) {
		return getArrString(str, ",");
	}

	public static boolean[] getArrboolean(String str) {
		StringTokenizer sto = new StringTokenizer(str, ",");
		boolean rr[] = new boolean[sto.countTokens()];
		int i = 0;

		while (sto.hasMoreTokens()) {
			rr[i] = StrToBoolean(sto.nextToken()).booleanValue();
			i++;
		}
		return rr;
	}

	public static Short getShort2(String str) {
		try {
			return new Short(str);
		} catch (Exception e) {
		}
		return new Short("0");
	}

	public static short getShort(String str) {
		return getShort2(str).shortValue();
	}

	public static Byte getByte3(String str) {
		try {
			return new Byte(str);
		} catch (Exception e) {
			return null;
		}
	}

	public static Byte getByte2(String str) {
		try {
			return new Byte(str);
		} catch (Exception e) {

		}
		return new Byte("0");
	}

	public static byte getByte(String str) {
		try {
			return new Byte(str).byteValue();
		} catch (Exception e) {
		}
		return new Byte("0").byteValue();
	}

	public static boolean isDate(String str) {
		try {
			SimpleDateFormat simpleDF = new SimpleDateFormat("yyyy-MM-dd");

			Date d = (Date) simpleDF.parse(str);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public static Date getDate4(String str) {
		try {
			if (str.length() > 19) {
				str = str.substring(0, 19);
			}
			SimpleDateFormat simpleDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			return (Date) simpleDF.parse(str);
		} catch (Exception e) {
			return getDate2(str);
		}
	}

	public static Date getDate3(String str) {
		try {
			SimpleDateFormat simpleDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			return (Date) simpleDF.parse(str);
		} catch (Exception e) {
			return getDate2(str);
		}
	}

	// 2008/12/4 上午 12:00:00
	public static Date getDate31_(String str) {
		try {
			SimpleDateFormat simpleDF = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
			return (Date) simpleDF.parse(str);
		} catch (Exception e) {
			return getDate2(str);
		}
	}

	public static Date getDate31(String str) {
		try {
			SimpleDateFormat simpleDF = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			return (Date) simpleDF.parse(str);
		} catch (Exception e) {
			return getDate2(str);
		}
	}

	public static Date getDate2(String str) {
		try {
			SimpleDateFormat simpleDF = new SimpleDateFormat("yyyy-MM-dd");

			return (Date) simpleDF.parse(str);
		} catch (Exception e) {
		}
		return null;
	}

	public static Date getDate2_(String str) {
		try {
			SimpleDateFormat simpleDF = new SimpleDateFormat("yyyy/MM/dd");

			return (Date) simpleDF.parse(str);
		} catch (Exception e) {
		}
		return null;
	}

	public static Date getDate(String str) {
		try {
			SimpleDateFormat simpleDF = new SimpleDateFormat("yyyy-MM-dd");

			return (Date) simpleDF.parse(str);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new Date(System.currentTimeMillis());
	}

	public static String getYMD(Date d) {
		try {
			SimpleDateFormat simpleDF = new SimpleDateFormat("yyyy年MM月dd日");
			return simpleDF.format(d).toString();
		} catch (Exception e) {
		}

		return "";
	}

	public static String getYMD1(Date d) {
		try {
			SimpleDateFormat simpleDF = new SimpleDateFormat("yyyy-MM-dd");
			return simpleDF.format(d).toString();
		} catch (Exception e) {
		}

		return "";
	}

	public static String getYMDHHMM(Date d) {
		try {
			SimpleDateFormat simpleDF = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			return simpleDF.format(d).toString();
		} catch (Exception e) {
		}

		return "";
	}

	public static String DateToStr3(Date d) {
		try {
			SimpleDateFormat simpleDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			return simpleDF.format(d).toString();
		} catch (Exception e) {

		}
		return "";
	}

	public static String getMMDDHHMM(Date d) {
		try {
			SimpleDateFormat simpleDF = new SimpleDateFormat("HH:mm");
			return simpleDF.format(d).toString();
		} catch (Exception e) {

		}
		return "";
	}

	public static String getHHMM(Date d) {
		try {
			SimpleDateFormat simpleDF = new SimpleDateFormat("HH:mm");
			return simpleDF.format(d).toString();
		} catch (Exception e) {

		}
		return "";
	}

	public static String getHHMMSS(Date d) {
		try {
			SimpleDateFormat simpleDF = new SimpleDateFormat("HH:mm:ss");
			return simpleDF.format(d).toString();
		} catch (Exception e) {

		}
		return "";
	}

	public static String DateToStr(Date d) {
		try {
			SimpleDateFormat simpleDF = new SimpleDateFormat("yyyy-MM-dd");
			return simpleDF.format(d).toString();
		} catch (Exception e) {
		}

		return "";
	}

	public static String DateToStr4(Date d) {
		try {
			SimpleDateFormat simpleDF = new SimpleDateFormat("yyyyMMddHHmmss");
			return simpleDF.format(d).toString();
		} catch (Exception e) {
		}

		return "";
	}

	public static String DateToStr41(Date d) {
		try {
			SimpleDateFormat simpleDF = new SimpleDateFormat("HH-mm-ss");
			return simpleDF.format(d).toString();
		} catch (Exception e) {
		}

		return "";
	}

	public static String DateToStr7(Date d) {
		try {
			SimpleDateFormat simpleDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			return simpleDF.format(d).toString();
		} catch (Exception e) {
		}

		return "";
	}

	public static String DateToStr8(Date d) {
		try {
			SimpleDateFormat simpleDF = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			return simpleDF.format(d).toString();
		} catch (Exception e) {
		}

		return "";
	}

	public static String DateToStr5(Date d) {
		try {
			SimpleDateFormat simpleDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			return simpleDF.format(d).toString();
		} catch (Exception e) {
		}

		return "";
	}

	public static String IntToStr(Integer i) {
		try {
			return i.toString();
		} catch (Exception e) {
		}
		return "";
	}

	public static String ShortToStr(short s) {
		try {
			Short ss = new Short(s);
			return ss.toString();
		} catch (Exception e) {
		}
		return "";
	}

	public static String ByteToStr(byte b) {
		try {
			Byte bb = new Byte(b);
			return bb.toString();
		} catch (Exception e) {
		}
		return "";
	}

	public String request_parameter(HttpServletRequest request) {

		String parameter = request.getParameter("parameter");
		if (parameter == null || parameter.trim().equals("")) {
			String action_ = request.getServletPath();
			Enumeration enu = request.getParameterNames();
			parameter = "?";
			while (enu.hasMoreElements()) {
				String para = (String) enu.nextElement();
				if (para != null && !para.trim().equals("")) {
					parameter = parameter + para + "=" + request.getParameter(para) + "&";
				}
			}
			parameter = action_ + parameter;
			if (parameter != null && !parameter.trim().equals("") && parameter.length() > 1) {
				parameter = parameter.substring(1, parameter.length() - 1);
			}
		}
		request.setAttribute("parameter", parameter);
		return "";
	}

	public static Boolean StrToBoolean(String str) {
		try {
			if (str.equalsIgnoreCase("1")) {
				return new Boolean(true);
			} else if (str.equalsIgnoreCase("0")) {
				return new Boolean(false);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	// asp中轉日期格式
	public static Date getAspDate(String str) {
		try {
			SimpleDateFormat simpleDF = new SimpleDateFormat("yyyy/MM/dd");
			return (Date) simpleDF.parse(str);
		} catch (Exception e) {
			return getAspDate2(str);
		}
	}

	public static Date getAspDate2(String str) {
		try {
			SimpleDateFormat simpleDF = new SimpleDateFormat("yyyy-MM-dd");
			return (Date) simpleDF.parse(str);
		} catch (Exception e) {

		}
		return null;
	}

	public static Date getAspDate3(String str) {
		try {
			SimpleDateFormat simpleDF = new SimpleDateFormat("yyyyMMddHH");
			return (Date) simpleDF.parse(str);
		} catch (Exception e) {

		}
		return null;
	}

	// 得到日期最大值
	public static int getmaxDay(int year, int month) {
		boolean value = Leep(year);
		int result = 0;
		if (month % 2 != 0) {
			return 31;
		} else {
			if (value) {
				if (month == 2) {
					result = 29;
				} else {
					result = 30;
				}
			} else {
				if (month == 2) {
					result = 28;
				} else {
					result = 30;
				}
			}
		}
		return result;
	}

	public static boolean Leep(int year) {
		boolean value;
		if ((year % 4) != 0)
			value = false;
		else {
			if ((year % 100) != 0)
				value = true;
			else {
				if ((year % 400) != 0)
					value = false;
				else
					value = true;
			}
		}
		return value;
	}

	public static String DateToStr(Date d, Integer mm, Integer dd) {
		try {
			int y = getInteger(getYYYY(d));
			int m = getInteger(getMM(d));
			int di = getInteger(getDD(d));
			if (mm != null) {
				m = m + mm;
			}
			if (dd != null) {
				di = di + dd;
			}
			Date tempdate = getDate2(y + "-" + m + "-" + di);
			return DateToStr(tempdate);
		} catch (Exception e) {
		}

		return "";
	}

	public static String getHH(Date d) {
		try {
			SimpleDateFormat simpleDF = new SimpleDateFormat("hh");
			return simpleDF.format(d).toString();
		} catch (Exception e) {
		}

		return "";
	}

	public static String getDD(Date d) {
		try {
			SimpleDateFormat simpleDF = new SimpleDateFormat("dd");
			return simpleDF.format(d).toString();
		} catch (Exception e) {
		}

		return "";
	}

	public static String getMM(Date d) {
		try {
			SimpleDateFormat simpleDF = new SimpleDateFormat("MM");
			return simpleDF.format(d).toString();
		} catch (Exception e) {
		}

		return "";
	}

	public static String getYYYY(Date d) {
		try {
			SimpleDateFormat simpleDF = new SimpleDateFormat("yyyy");
			return simpleDF.format(d).toString();
		} catch (Exception e) {
		}
		return "";
	}

	public static String getMD(Date d) {
		try {
			SimpleDateFormat simpleDF = new SimpleDateFormat("yyyyMMdd");
			return simpleDF.format(d).toString();
		} catch (Exception e) {
		}
		return "";
	}

	public static void errorlog(Log log, Class clazz, Exception e) {
		if (log.isErrorEnabled()) {
			// e.printStackTrace();
			log.error(clazz + " : " + e.getMessage());
		}
	}

	public static String getIP(String path) {
		if (path != null && !path.trim().equals("")) {
			int c = path.lastIndexOf("192");

			if (c != -1) {
				String temp = path.substring(c, path.length());

				int indexOf = 10000;
				if (temp != null) {
					if (temp.indexOf("\\") != -1) {
						if (temp.indexOf("\\") < indexOf)
							indexOf = temp.indexOf("\\");
					}
					if (temp.indexOf("/") != -1) {
						if (temp.indexOf("/") < indexOf)
							indexOf = temp.indexOf("/");
					}

				}
				if (temp != null && indexOf != -1 && indexOf != 10000) {
					temp = temp.substring(0, indexOf);
				}
				return temp;
			}

		}

		return "";
	}

	/**
	 * jiang
	 * 
	 * @param temp
	 * @return
	 */
	public static String getSize(double fileSize) {
		if (fileSize > 1000) {
			fileSize = div(fileSize, 1024.00, 2);
			if (fileSize >= 1000) {
				fileSize = div(fileSize, 1024.00, 2);
				if (fileSize >= 1000) {
					fileSize = div(fileSize, 1024.00, 2);
					return fileSize + " GB";
				} else {
					return fileSize + " MB";
				}
			} else {
				return fileSize + " KB";
			}
		} else {
			return fileSize + " B";
		}
	}

	public static boolean isGOT(String publishno) {

		if (publishno.toLowerCase().lastIndexOf("gto") != -1) {
			return true;
		}
		return false;
	}

	public void writerStringToFile(String str, String filePath) {
		Writer writer = null;
		try {
			writer = new OutputStreamWriter(new FileOutputStream(filePath), "UTF-8");
			writer.write(str);
			writer.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (writer != null) {
					writer.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 複製流,複製完成返回複製的字節數
	 * 
	 * @param in
	 *          輸入流
	 * @param out
	 *          輸出流
	 * @param autoClose
	 *          完成複製後是否關閉流，如指定為false需複製完後手工關閉輸入輸出流
	 * @return 複製總字節數
	 * 
	 * @throws IOException
	 */
	public static long copy(InputStream in, OutputStream out, boolean autoClose) throws IOException {
		int len = 0;
		long count = 0L;
		byte[] buffer = new byte[4096];
		try {
			while ((len = in.read(buffer)) != -1) {
				out.write(buffer, 0, len);
				count = count + len;
			}
			out.flush();
		} finally {
			if (autoClose) {
				closeQuietly(in);
				closeQuietly(out);
			}
		}
		return count;
	}

	/**
	 * 複製流，完成複製後不會關閉輸入輸出流，需手工關閉
	 * 
	 * @param in
	 *          輸入流
	 * @param out
	 *          輸出流
	 * 
	 * @return 複製總字節數
	 * 
	 * @throws IOException
	 */
	public static long copy(InputStream in, OutputStream out) throws IOException {
		return copy(in, out, false);
	}

	/**
	 * 複製文件
	 * 
	 * @param source
	 *          源文件
	 * @param destination
	 *          目標文件
	 * @throws IOException
	 */
	public static void copyFile(File source, File destination) throws IOException {
		if (source.isDirectory()) {
			if (destination.exists() && destination.isFile()) {
				throw new IOException("Destination '" + destination + "' exists but it's a file");
			}
			File outDir = new File(destination, source.getName());
			if (!outDir.mkdirs()) {
				throw new IOException("Directory '" + outDir + "' could not be created");
			}
			File[] ls = source.listFiles();
			if (ls == null) {
				throw new IOException("Failed to list contents of " + source);
			}
			for (File child : ls) {
				copyFile(child, new File(outDir, child.getName()));
			}
		} else {
			InputStream in = openInputStream(source);
			try {
				// 如果目標存在且是文件夾
				if (destination.exists() && destination.isDirectory()) {
					destination = new File(destination, source.getName());
				}
				OutputStream out = openOutputStream(destination);
				try {
					copy(in, out);
				} finally {
					closeQuietly(out);
				}
			} finally {
				closeQuietly(in);
			}
		}
	}

	/**
	 * 關閉輸入流,不拋出異常
	 * 
	 * @param in
	 *          輸入流
	 */
	public static void closeQuietly(InputStream in) {
		try {
			if (in != null) {
				in.close();
			}
		} catch (Exception e) {
		}
	}

	/**
	 * 關閉輸出流,不拋出異常
	 * 
	 * @param out
	 *          輸出流
	 */
	public static void closeQuietly(OutputStream out) {
		try {
			if (out != null) {
				out.close();
			}
		} catch (Exception e) {
		}
	}

	/**
	 * 打開一個文件輸入流，從指定的文件讀取數據
	 * 
	 * @param file
	 * @return
	 * @throws IOException
	 */
	public static FileInputStream openInputStream(File file) throws IOException {
		return new FileInputStream(file);
	}

	/**
	 * 打開一個文件輸出流，將數據寫入到指定文件
	 * 
	 * @param file
	 * @return
	 * @throws IOException
	 */
	public static FileOutputStream openOutputStream(File file) throws IOException {
		File parent = file.getParentFile();
		if (parent != null && !parent.exists()) {
			if (!parent.mkdirs()) {
				throw new IOException("File '" + file + "' could not be created");
			}
		}
		return new FileOutputStream(file);
	}

	/**
	 * 获取文件扩展名
	 * 
	 * @param file
	 * 
	 * @return
	 */
	public static String getFileExtensions(File file) {
		String fileName = file.getName();
		if (fileName.lastIndexOf(".") == -1) {
			return "";
		} else {
			return fileName.substring(fileName.lastIndexOf(".") + 1);
		}
	}

	/**
	 * 將日期/時間值格式化為字符串
	 * 
	 * @param date
	 *          待格式化的日期/時間值
	 * @param pattern
	 *          輸出格式
	 * @return 格式化的时间字符串。
	 */
	public static String formatDate(Date date, String pattern) {
		return new SimpleDateFormat(pattern).format(date);
	}

	/**
	 * 將日期/時間值格式化為字符串,默認輸出格式為yyyy-MM-dd HH:mm:ss
	 * 
	 * @param date
	 *          待格式化的日期/時間值
	 * @return 格式化的时间字符串。
	 */
	public static String formatDate(Date date) {
		return formatDate(date, "yyyy-MM-dd HH:mm:ss");
	}

	/**
	 * 發送成功失敗狀態響應
	 * 
	 * @param flag
	 * @param response
	 */
	public static void sendResponseXML(boolean flag, HttpServletResponse response) {
		Document doc = DocumentHelper.createDocument();
		doc.addElement("status").addElement("value").setText((flag ? "1" : "0"));
		sendResponseXML(doc, response);
	}

	/**
	 * 發送自定義響應狀態
	 * 
	 * @param flag
	 * @param response
	 */
	public static void sendResponseXML(int flag, HttpServletResponse response) {
		Document doc = DocumentHelper.createDocument();
		doc.addElement("status").addElement("value").setText(String.valueOf(flag));
		sendResponseXML(doc, response);
	}

	/**
	 * 向response輸出XML
	 * 
	 * @param doc
	 *          待輸出XML
	 * @param response
	 *          HttpServletResponse
	 */
	public static void sendResponseXML(Document doc, HttpServletResponse response) {
		try {
			response.setCharacterEncoding("UTF-8");
			response.setContentType("text/xml;charset=UTF-8");

			OutputFormat format = OutputFormat.createPrettyPrint();
			format.setEncoding("UTF-8");

			XMLWriter writer = new XMLWriter(response.getOutputStream(), format);
			writer.write(doc);
			writer.flush();
			writer.close();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 计算字符串MD5值
	 * 
	 * @param str
	 * @return
	 * @throws Exception
	 */
	public static String getMD5String(String str) throws Exception {
		MessageDigest md = MessageDigest.getInstance("MD5");
		StringBuffer sb = new StringBuffer(32);

		md.update(str.getBytes("UTF-8"));

		byte[] result = md.digest();

		for (byte b : result) {
			int i = b & 0xff;
			if (i < 0xf) {
				sb.append("0");
			}
			sb.append(Integer.toHexString(i));
		}
		return sb.toString();
	}
}